package com.shuaiqidefeng.PDFToJPG;

import jakarta.servlet.ServletException;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.annotation.MultipartConfig;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.Part;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

@WebServlet("/PDFToJPG")
@MultipartConfig
public class PDFToJPG extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        long beginTime = System.currentTimeMillis();
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");
        Part part = req.getPart("file");

        String filePath = req.getServletContext().getRealPath("/");
        String fileName = part.getSubmittedFileName();
        String fileRealPath = filePath + "/" + fileName;
        //判断是否为pdf文件
        PDFTool pdfTool = new PDFTool();
        Result isPDFFileResult = pdfTool.isPDFFile(fileName);
        //否
        if (!isPDFFileResult.isSucces){
            resp.getWriter().write(isPDFFileResult.result);
            resp.getWriter().close();
        }
        //是
        part.write(fileRealPath);
        File file = new File(fileRealPath);
        //转pdf
        Result PDFToJPGResult = pdfTool.pdfbox(file);
        //压缩
        if (!PDFToJPGResult.isSucces){
            resp.getWriter().write(PDFToJPGResult.result);
            resp.getWriter().close();
        }
        ZipTool zipTool = new ZipTool();
        Result zipResult = zipTool.zipFiles(PDFToJPGResult.getFile());//获取根目录
        //下载
        req.setCharacterEncoding("UTF-8");
        resp.setContentType("application/x-msdownload");
        //设置下载的文件名
        System.out.println("begin download");
        resp.setHeader("Content-Disposition","attachment;filename="+zipResult.getFile().getName());
        InputStream inputStream = new FileInputStream(zipResult.getFile());
        //输出流
        ServletOutputStream outputStream = resp.getOutputStream();
        int len = 0;
        byte[] bytes = new byte[1024];
        while ((len = inputStream.read(bytes)) != -1){
            outputStream.write(bytes,0,len);
        }
        outputStream.close();
        inputStream.close();

        FileTool fileTool = new FileTool();
        System.out.println(fileTool.deleteFile(PDFToJPGResult.getFile()));
        System.out.println(zipResult.getFile().delete());
        System.out.println(file.delete());
        long finishTime = System.currentTimeMillis();
        System.out.println(finishTime-beginTime);
    }
}
